package com.googlecode.connectlet.web;

import java.io.IOException;
import java.security.cert.X509Certificate;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ssl.SslSocketConnector;
import org.eclipse.jetty.servlet.ServletHandler;

import com.googlecode.connectlet.ssl.CertMap;
import com.googlecode.connectlet.util.ClassPath;

public class TestHttps extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
		if (certs != null) {
			response.setContentType("application/x-pkcs7-certificates");
			CertMap.exportPkcs7(certs).encodeSignedData(response.getOutputStream());
		}
	}

	public static void main(String[] args) throws Exception {
		Server server = new Server();
		SslSocketConnector connector = new SslSocketConnector();
		connector.setKeystoreType("PKCS12");
		connector.setKeystore(ClassPath.getInstance("../conf/localhost.pfx").getPath());
		connector.setKeyPassword("changeit");
		connector.setTruststoreType("PKCS12");
		connector.setTruststore(ClassPath.getInstance("../conf/localhost.pfx").getPath());
		connector.setTrustPassword("changeit");
		connector.setPassword("changeit");
		connector.setWantClientAuth(true);
		connector.setPort(443);
		server.addConnector(connector);
		ServletHandler handler = new ServletHandler();
		handler.addServletWithMapping(TestHttps.class, "/");
		server.setHandler(handler);
		server.start();
		server.join();
	}
}